package com.yuyou.hxyy.gateway.security;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import com.yuyou.hxyy.service.api.bean.ResBoolSimpleInfo;
import com.yuyou.hxyy.service.api.mess.LoginMess;
import com.yuyou.hxyy.service.api.service.ILoginService;
import com.yuyou.hxyy.service.api.vo.req.ReqLogin;
import com.yuyou.hxyy.service.api.vo.resp.RespLogin;

/**
 * 登陆验证逻辑
 *
 */
@Component
public class AuthenticationProviderImpl implements AuthenticationProvider {
    @Autowired
    private UserDetailsServiceImpl userService;
    @Autowired
    private ILoginService loginService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    	WebAuthenticationDetailsImpl details = (WebAuthenticationDetailsImpl) authentication.getDetails();      
        String username = details.getPhone();
        String password = details.getPassword();
        String captcha =details.getCaptcha();
        String token =details.getToken();
        String userType =details.getUserType();
        
        UserDetailsImpl userDetials = (UserDetailsImpl) userService.loadUserByUsername(username);
        if(userDetials == null){
            throw new BadCredentialsException(LoginMess.ERR_UPDATE_PASSWORD);
        }             
        ResBoolSimpleInfo<RespLogin> res=loginService.login(new ReqLogin(username,password,Integer.parseInt(userType),captcha,token));
        if(res.isSuccess()){
        	RespLogin resp=res.getData();
        	userDetials.setResp(resp);
            Collection<? extends GrantedAuthority> authorities = userDetials.getAuthorities();        
            return new UsernamePasswordAuthenticationToken(userDetials, password, authorities);
        }else{
        	throw new BadCredentialsException(res.getMessage());
        }
    }
    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }

}